<?php

namespace App\Http\Controllers\Home;

use App\Http\Controllers\Controller;
use App\Services\Home\ArticleService;
use App\Services\Home\CategoryService;
use App\Services\RedisService;

class ArticleController extends Controller
{
    use RedisService;

    protected $category, $article;

    public function __construct(CategoryService $category, ArticleService $article)
    {
        $this->category = $category;
        $this->article = $article;
    }

    //curl获取请求文本内容
    public function get_curl_contents($url, $method ='GET', $data = array()) {
        if ($method == 'POST') {
            //使用crul模拟
            $ch = curl_init();
            //禁用htt<a href="/fw/photo.html" target="_blank">ps</a>

            //允许请求以文件流的形式返回
            curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
            curl_setopt($ch, CURLOPT_POST, 1);
            curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($data));
            curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 30);
            curl_setopt($ch, CURLOPT_DNS_CACHE_TIMEOUT, 30);
            curl_setopt($ch, CURLOPT_URL, $url);
            $result = curl_exec($ch); //执行发送
            curl_close($ch);
        }else {
            if (ini_get('allow_<a href="/tags.php/fopen/" target="_blank">fopen</a>_url') == '1') {
                $result = file_get_contents($url);
            }else {
                //使用crul模拟
                $ch = curl_init();
                //允许请求以文件流的形式返回
                curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
                //禁用https
                curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
                curl_setopt($ch, CURLOPT_URL, $url);
                $result = curl_exec($ch); //执行发送
                curl_close($ch);
            }
        }
        return $result;
    }

    //获取微信公从号access_token
    function wx_get_token() {

        $access_token = $this->redisSingleGet('weixin.access_token');

        if (!$access_token) {
            $AppID = env('WEIXIN.APPID');//AppID(应用ID)
            $AppSecret = env('WEIXIN.APPSECRET');//AppSecret(应用密钥)
            $url = 'https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid='.$AppID.'&secret='.$AppSecret;
            $res = $this->get_curl_contents($url);
            $res = json_decode($res, true);
            //这里应该把access_token缓存起来，至于要怎么缓存就看各位了，有效期是7200s

            $this->redisSingleAdd('weixin.access_token', $res['access_token'], 7200);

            return $res['access_token'];
        }

        return $access_token;
    }

    //获取微信公从号ticket
    public function wx_get_jsapi_ticket()
    {
        $ticket = $this->redisSingleGet('weixin.ticket');

        if (!$ticket) {
            $url = sprintf("https://api.weixin.qq.com/cgi-bin/ticket/getticket?access_token=%s&type=jsapi", $this->wx_get_token());
            $res = $this->get_curl_contents($url);
            $res = json_decode($res, true);
            //这里应该把access_token缓存起来，至于要怎么缓存就看各位了，有效期是7200s

            $this->redisSingleAdd('weixin.ticket', $res['ticket'], 7200);

            return $res['ticket'];
        }

        return $ticket;
    }

    public function view($article_id)
    {
        //当前文章内容
        $article = $this->article->first($article_id);

        $wx['appid'] = env('WEIXIN.APPID');

        //生成签名的时间戳
        $wx['timestamp'] = time();

        //生成签名的随机串
        $wx['noncestr'] = 'Wm3WZYTPz0wzccnW';

        //jsapi_ticket是公众号用于调用微信JS接口的临时票据。正常情况下，jsapi_ticket的有效期为7200秒，通过access_token来获取。

        $wx['jsapi_ticket'] = $this->wx_get_jsapi_ticket();
        //分享的地址，注意：这里是指当前网页的URL，不包含#及其后面部分，曾经的我就在这里被坑了，所以小伙伴们要小心了

        $wx['url'] = 'http://'.$_SERVER['HTTP_HOST'].$_SERVER['REQUEST_URI'];

        $string = sprintf("jsapi_ticket=%s&noncestr=%s&timestamp=%s&url=%s", $wx['jsapi_ticket'], $wx['noncestr'], $wx['timestamp'], $wx['url']);

        //生成签名
        $wx['signature'] = sha1($string);

        return view('home.article.view', [
            'article' => $article,
            'pre_article' => $pre_article ?? ['id' => $article_id, 'title' => '没有了'],
            'next_article' => $next_article ?? ['id' => $article_id, 'title' => '没有了'],
            'wx' => $wx,
        ]);
    }
}